import fs from 'node:fs'

export const ROOT_PATH = process.cwd() // __dirname

export function delayTime(time: number) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(true)
    }, time)
  })
}

export function writeFileStr(path: string, fileStr: string) {
  try {
    fs.writeFileSync(path, fileStr, {
      flag: 'w'
    })
  }
  catch (e) {
    console.error(e)
  }
}

export function delateFile(path: string) {
  try {
    fs.unlinkSync(path)
  }
  catch (err) {
    console.log(err)
  }
}

export function isDirectory(path: string) {
  const stat = tryStatSync(path)
  return stat?.isDirectory() ?? false
}

export function isFile(path: string) {
  const stat = tryStatSync(path)
  return stat?.isFile() ?? false
}

function tryStatSync(file: string) {
  try {
    // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
    return fs.statSync(file, { throwIfNoEntry: false })
  }
  catch {
    // Ignore errors
  }
}

export function camelToHyphen(str: string) {
  return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}
